import { Input, InputNumber } from 'ant-design-vue';
import { inputValueToInt, isNewPatternClasses, strToArr } from '@/util/index.js';
import { ref } from 'vue';

export function useClasses({ loading }) {
  const classesColumns = ref([
    {
      title: '标签',
      dataIndex: 'label',
      customRender: ({ record, text }) => (
        <Input
          value={text}
          disabled={loading.value}
          onBlur={event => (record.label = event.currentTarget.value)}>
        </Input>
      ),
    },
    {
      width: 110,
      title: '限量',
      dataIndex: 'limit',
      customRender: ({ record, text }) => (
        <InputNumber
          value={text}
          disabeld={loading.value}
          min={1}
          max={100}
          step={1}
          onBlur={event => {
            record.limit = R.compose( R.clamp(1, 100), inputValueToInt )(event);
          }}
          onStep={value => (record.limit = value)}>
        </InputNumber>
      ),
    },
  ]);
  
  /**
   * 1. 区分逗号分隔词汇的旧格式和对象数组的新格式
   * 2. 旧格式最多可选量设为 `1e2`
   * 3. 新格式 `JSON.parse()`
   */
  const fromStorable = R.ifElse(
    isNewPatternClasses,
    R.curryN(1, JSON.parse),
    R.compose(
      R.map(label => ({ label, limit: 100 })),
      strToArr(R.split(','))
    )
  );

  const toStorable = R.curryN(1, JSON.stringify);

  return {
    classesColumns,
    fromStorable,
    toStorable,
  };
}
